<template>
  <el-form
    v-show="getShow"
    ref="formSmsLogin"
    :model="smsLoginFormInput"
    :rules="rules"
    class="login-form"
    label-position="top"
    label-width="120px"
    size="large"
  >
    <el-row style="margin-right: -10px; margin-left: -10px">
      <!-- 租户名 -->
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item v-if="smsLoginConfig.TenantEnable" prop="TenantName">
          <el-input
            v-model="smsLoginFormInput.TenantName"
            :placeholder="t('login.tenantNamePlaceholder')"
            :prefix-icon="iconHouse"
            type="primary"
            link
          />
        </el-form-item>
      </el-col>
      <!-- 手机号 -->
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item prop="Mobile">
          <el-input
            v-model="smsLoginFormInput.Mobile"
            :placeholder="t('login.mobileNumberPlaceholder')"
            :prefix-icon="iconCellphone"
          />
        </el-form-item>
      </el-col>
      <!-- 验证码 -->
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item prop="SmsCode">
          <el-row :gutter="5" justify="space-between" style="width: 100%">
            <el-col :span="24">
              <el-input
                v-model="smsLoginFormInput.SmsCode"
                :placeholder="t('login.codePlaceholder')"
                :prefix-icon="iconCircleCheck"
              >
                <!-- <el-button class="w-[100%]"> -->
                <template #append>
                  <span
                    v-if="mobileCodeTimer <= 0"
                    class="getMobileCode"
                    style="cursor: pointer"
                    @click="getSmsCode"
                  >
                    {{ t('login.getSmsCode') }}
                  </span>
                  <span v-if="mobileCodeTimer > 0" class="getMobileCode" style="cursor: pointer">
                    {{ mobileCodeTimer }}秒后可重新获取
                  </span>
                </template>
              </el-input>
              <!-- </el-button> -->
            </el-col>
          </el-row>
        </el-form-item>
      </el-col>
      <!-- 登录按钮 / 返回按钮 -->
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <XButton
            :loading="loginLoading"
            :title="t('login.login')"
            class="w-[100%]"
            type="primary"
            @click="signIn()"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
        <el-form-item>
          <XButton
            :loading="loginLoading"
            :title="t('login.backLogin')"
            class="w-[100%]"
            @click="handleBackLogin()"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script lang="ts" setup>
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import { useIcon } from '@/hooks/web/useIcon'
import { usePermissionStore } from '@/store/modules/permission'
import { getTenantIdByName, sendSmsCode, smsLogin } from '@/api/login'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'
import { ElLoading, FormInstance } from 'element-plus'
import { LoginSmsFromParam, SmsLoginReq } from '@/models/auth/LoginUserModel'
import cache from '@/utils/cache'
import { CacheKey } from '@/utils/globalConstants'
import { TokenInfo } from '@/models/auth/TokenModel'
import { ProcessingStatus } from '@/config/processingStatus'

defineOptions({ name: 'MobileForm' })

const { t } = useI18n()
const message = useMessage()
const permissionStore = usePermissionStore()
const { currentRoute, push } = useRouter()
const formSmsLogin = ref<FormInstance>()
const loginLoading = ref<boolean>(false)
const iconHouse = useIcon({ icon: 'ep:house' })
const iconCellphone = useIcon({ icon: 'ep:cellphone' })
const iconCircleCheck = useIcon({ icon: 'ep:circle-check' })
const { validForm } = useFormValid(formSmsLogin)
const { handleBackLogin, getLoginState } = useLoginState()
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.MOBILE)

// 验证规则
const rules = {
  TenantName: [required],
  Mobile: [required],
  SmsCode: [required]
}

// 登录输入参数
const smsLoginFormInput = reactive<LoginSmsFromParam>({
  TenantName: '',
  Mobile: '',
  SmsCode: '',
  Uuid: ''
})

// 手机登录配置参数
const smsLoginConfig = reactive({
  CodeImg: '',
  TenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE as unknown as boolean,
  Token: '',
  Loading: {
    SignIn: false
  }
})

const mobileCodeTimer = ref<number>(0)
const redirect = ref<string>('')
const getSmsCode = async () => {
  await getTenantId()
  const res = await sendSmsCode({ Mobile: smsLoginFormInput.Mobile })
  if (!res || res.Status !== ProcessingStatus.ProcessingSuccess) {
    message.warning(res.Message)
    return
  }
  message.success(t('login.SmsSendMsg'))
  // 设置倒计时
  mobileCodeTimer.value = 60
  const msgTimer = setInterval(() => {
    mobileCodeTimer.value = mobileCodeTimer.value - 1
    if (mobileCodeTimer.value <= 0) {
      clearInterval(msgTimer)
    }
  }, 1000)
}

watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)
// 获取租户 ID
const getTenantId = async () => {
  if (!smsLoginConfig.TenantEnable) return
  const res = await getTenantIdByName({ Name: smsLoginFormInput.TenantName })
  if (res && res.Status === ProcessingStatus.ProcessingSuccess && res.Data) {
    cache.writeCache(`${res.Data.Id}`, CacheKey.TenantId)
  }
}
// 登录
const signIn = async () => {
  try {
    await getTenantId()
    const data = await validForm()
    if (!data) return
    ElLoading.service({
      lock: true,
      text: '正在加载系统中...',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    loginLoading.value = true
    const smsLoginReq: SmsLoginReq = {
      Mobile: smsLoginFormInput.Mobile,
      SmsCode: smsLoginFormInput.SmsCode
    }

    const res = await smsLogin(smsLoginReq)
    if (!res || res.Status !== ProcessingStatus.ProcessingSuccess || !res.Data) {
      message.warning(res.Message)
      loginLoading.value = false
      return
    }
    cacheCurrentToken(res.Data.accessToken, res.Data.refreshToken, res.Data.expiresIn)
    if (!redirect.value) {
      redirect.value = '/'
    }
    push({ path: redirect.value || permissionStore.addRouters[0].path })
  } catch (error) {
    loginLoading.value = false
  } finally {
    loginLoading.value = false
    setTimeout(() => {
      const loadingInstance = ElLoading.service()
      loadingInstance.close()
    }, 400)
  }
}

// 缓存当前 Token
const cacheCurrentToken = (accessToken: string, refreshToken: string, exp?: number) => {
  const tokenInfo: TokenInfo = {
    AccessToken: accessToken,
    RefreshToken: refreshToken,
    ExpiresIn: exp as number
  }
  cache.setToken(tokenInfo)
}
</script>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.smsbtn {
  margin-top: 33px;
}
</style>
